package com.ss.springboot1.config.advice;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.ss.springboot1.common.exception.DeviceBusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器，统一处理应用中的异常
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.ss.springboot1.device.controller")
public class DeviceGlobalExceptionHandler {
    @ExceptionHandler(JsonProcessingException.class)
    public ResponseEntity<String> handleJsonProcessingException(JsonProcessingException e) {
        log.error("JSON处理异常", e);
        return ResponseEntity.badRequest().body("设备响应格式错误，请检查设备状态");
    }

    /**
     * 处理运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<String> handleRuntimeException(RuntimeException e) {
        log.error("运行时异常", e);
        return ResponseEntity.badRequest().body("操作失败");
    }

    /**
     * 处理设备业务异常
     */
    @ExceptionHandler(DeviceBusinessException.class)
    public ResponseEntity<String> handleDeviceBusinessException(DeviceBusinessException e) {
        log.error("设备业务异常: {}", e.getMessage());
        return ResponseEntity.badRequest().body(e.getMessage());
    }

    /**
     * 处理所有未捕获的异常
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleException(Exception e) {
        log.error("未知异常", e);
        return ResponseEntity.internalServerError().body("系统异常，请联系管理员");
    }
}

